/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csc668868webappteamsp12aproject1;

/**
 * Parses a line from products.txt into strings which are stored
 * in a ProductSpecification object.
 * inputs: filename.txt
 * output: ProductSpecification object or null if reached EOF
 * @author Jeff Hung
 */
public class ProductReader {
    private boolean atEOF = false;
    private char ch; // next character to process
    private SourceReader source = null;
    private ProductSpecification thisProduct;

/**
 *  Construct a new ProductReader
 */    
    public ProductReader(String sourceFile) throws Exception {
        source = new SourceReader(sourceFile);
        ch = source.read();
    }
    
    public ProductSpecification getNextProduct() {
        if(atEOF) {
            if(source!=null) {
                source.close();
                source = null;
            }
            return null;
        }
        String temp = "";
        thisProduct = new ProductSpecification();
        try {
            //get upc
            for(int i=1; i<5; i++) {
                temp = temp + ch;
                ch = source.read();
            }
            thisProduct.setUPC(temp);
            
            //get description
            temp = "";
            for(int i=5; i<10; i++) {
                ch = source.read(); //throw away spaces
            }
            for(int i=10; i<30; i++) {
                temp = temp + ch;
                ch = source.read();
            }            
            thisProduct.setDescription(temp);            
 
            //get price
            temp = "";
            for(int i=30; i<35; i++) {
                ch = source.read(); //throw away spaces
            }
            int currentLineno = source.getLineno();
            while(currentLineno == source.getLineno()) {
                int ascii_ch = (int) ch;
                if (ascii_ch == 32) {
                    thisProduct.setPrice(temp);
                } else {
                    temp = temp + ch;
                }
                ch = source.read();
            }            
        } catch (Exception e) {
            atEOF = true;
        }        
        return thisProduct;
    }
}
